const app = getApp()
var Encrypt = require('../../utils/jsencrypt.min.js')

import Toast from '@vant/weapp/toast/toast';
Page({
	data: {
		active: false,
		open: false,
		name: '',
		pwd: '',
		type:null,
		activeTab: 1
	},
	tabChange(e) {
		let type = e.detail.index==0?2:1
		this.setData({
			type:type,
		})
	},
	encrypt(p) {
	    let pubKey = "-----BEGIN PUBLIC KEY-----\n" +
	            "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC3FSbVbS78x4ygPWs84MccmVGT\n" +
	            "eBbXmd6B5V1wJL+nL+uBnes99bMEFUQHwH1SrUyk3zHYjgZuKEQmLSB6BtUOwln6\n" +
	            "HdA0zEBZTQzzLnWGdQKKFJhTtTEGQqhT0buQyxD7OqveOfSzKeBClvAyXqV4ZLQw\n" +
	            "iOrkKHIPNJg6OhhMjwIDAQAB\n" +
	            "-----END PUBLIC KEY-----"
	    let ras = new Encrypt.JSEncrypt()
	    ras.setPublicKey(pubKey);
	    let np = ras.encrypt(p)
	    return np;
	},
	onLoad(options) {

	},
	toReg(){
		wx.navigateTo({
			url: "/pages/login/reg?type="+ this.data.type
		})
	},
	changeActive() {
		let a = !this.data.active;
		this.setData({
			active: a
		})
	},
	switch () {
		this.setData({
			open: !this.data.open
		})
	},
	noTap() {
		wx.showToast({
			title: '请先勾选《用户使用协议》与《隐私权条款》',
			icon: 'none'
		})
	},

	submit() {
		if(this.data.name == ''){
			Toast('请输入账号！')
		}else if(this.data.pwd == ''){
			Toast('请输入密码！')
		}else{
			app.indexApi.login({
				username: this.data.name,
				password: this.encrypt(this.data.pwd),
				type:this.data.type
			}).then(a => {
				if (a.code == 0) {
					wx.setStorageSync('token', a.data.token)
					delete(a.data.token);
					if (!a.data.avatar) {
						a.data.avatar = 'upfiles/static/user_default.png'
					}
					wx.setStorageSync('user', JSON.stringify(a.data))
					wx.showToast({
						title: '登录成功',
						icon: 'success',
						duration:1500
					})
					const timer = setInterval(() => {
					  wx.redirectTo({
					  	url: "/pages/index/index"
					  })
					  clearInterval(timer);
					}, 2000);
					
				} else {
					wx.showToast({
						title: a.msg,
						icon: 'none'
					})
				}
			})
		}
		

	}
})